package demo1.service;


import demo1.dao.Mapper.goodsMapper;
import demo1.dao.Mapper.userMapper;
import demo1.dao.sql.goodsSql;
import demo1.dao.sql.userSql;
import demo1.pojo.*;

import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.*;

public class goodsService {
    public List<goods> selectAll() throws Exception {//显示所有的商品
        goodsMapper goodsMapper = new goodsSql();
        //把未支付的订单的库存还回来
        userMapper userMapper = new userSql();
        ResultSet rs = userMapper.selectAllOrderForm();
        while (rs.next()){
            if(((rs.getInt("statue") == 0) || (rs.getInt("statue") == 2)) && (rs.getInt("goods_handle") == 0)){
                //没有支付成功的,还没有被处理的,已经取消了的订单
                if((rs.getInt("statue") == 0)){
                    Timestamp time = rs.getTimestamp("time");
                    // 获取当前时间的Date
                    Date currentDate = new Date();
                    // 比较时间
                    if (time.before(currentDate)) {
                        //时间过了
                        int goodsID = rs.getInt("goods_id");
                        int goodsNum = rs.getInt("goods_num");
                        ResultSet rs2 = goodsMapper.selectByID(goodsID);
                        int goodsNum2 = 0;
                        if (rs2.next()) {
                            goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                        }
                        goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                        userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                    }
                }
                else if ((rs.getInt("statue") == 2)) {
                    int goodsID = rs.getInt("goods_id");
                    int goodsNum = rs.getInt("goods_num");
                    ResultSet rs2 = goodsMapper.selectByID(goodsID);
                    int goodsNum2 = 0;
                    if (rs2.next()) {
                        goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                    }
                    goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                    userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                }

            }
        }
        return goodsMapper.selectAllEarly();
    }
    public PageBean<goods> showUserMaiGoods(int currentPage,int pageSize, int userID) throws Exception {
        goodsMapper goodsMapper = new goodsSql();
        //把未支付的订单的库存还回来
        userMapper userMapper = new userSql();
        ResultSet rs = userMapper.selectAllOrderForm();
        while (rs.next()){
            if(((rs.getInt("statue") == 0) || (rs.getInt("statue") == 2)) && (rs.getInt("goods_handle") == 0)) {
                //没有支付成功的,还没有被处理的,已经取消了的订单
                if ((rs.getInt("statue") == 0)) {
                    Timestamp time = rs.getTimestamp("time");
                    // 获取当前时间的Date
                    Date currentDate = new Date();
                    // 比较时间
                    if (time.before(currentDate)) {
                        //时间过了
                        int goodsID = rs.getInt("goods_id");
                        int goodsNum = rs.getInt("goods_num");
                        ResultSet rs2 = goodsMapper.selectByID(goodsID);
                        int goodsNum2 = 0;
                        if (rs2.next()) {
                            goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                        }
                        goodsMapper.modifyGoodsNum((goodsNum + goodsNum2), goodsID);
                        userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                    }
                } else if ((rs.getInt("statue") == 2)) {
                    int goodsID = rs.getInt("goods_id");
                    int goodsNum = rs.getInt("goods_num");
                    ResultSet rs2 = goodsMapper.selectByID(goodsID);
                    int goodsNum2 = 0;
                    if (rs2.next()) {
                        goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                    }
                    goodsMapper.modifyGoodsNum((goodsNum + goodsNum2), goodsID);
                    //userMapper.updateOrderFormStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                    userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                }
            }
        }
        //计算开始索引
        int begin = (currentPage-1) * pageSize;
        int size = pageSize;
        //goodsMapper goodsMapper = new goodsSql();
        List<goods> rows = goodsMapper.selectByPageMai(begin, size,userID);
        //查询总记录数
        int totalCount = goodsMapper.selectTotalCountsMai(userID);

        //封装对象
        PageBean<goods> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);


        return pageBean;
    }
    public int modifyGoods(goods goods)throws Exception{//修改商品信息
        String goodsName = goods.getGoodsName();
        String goodsMessage = goods.getGoodsMessage();
        String statue = goods.getStatue();
        String goodsType = goods.getGoodsType();
        int goodsNum = goods.getGoodsNum();
        int goodsID = goods.getGoodsID();
        float price = goods.getPrice();

        int goodsNameLenth = goodsName.length();//初始字符串长度
        int goodsMessageLenth = goodsMessage.length();//初始字符串长度

        goodsMessage = goodsMessage.replaceAll("\\s+", "");//去除所有的空格
        goodsName = goodsName.replaceAll("\\s+", "");//去除所有的空格

        int goodsNameLenth2 = goodsName.length();//后来的字符串长度
        int goodsMessageLenth2 = goodsMessage.length();//后来的字符串长度

        if ((goodsNameLenth != goodsNameLenth2) || (goodsMessageLenth != goodsMessageLenth2) || (goodsNum < 0) || (price == 0) || (goodsName.isEmpty())|| (goodsMessage.isEmpty())){
            //价格为空，库存为空，库存为负数，商品信息含有空格，商品名称含有空格，商品信息商品名称为空,返回0
            return 0;
        } else {
            goodsMapper goodsMapper = new goodsSql();
            //先读取数据库里面的商品状态，如果同样是上架就不改变上架时间，如果从下架变成上架就改变时间
            ResultSet rs = goodsMapper.selectByID(goodsID);
            String statue2 = null;
            if (rs.next()) {
                statue2 = rs.getString("statue");
            }
            if (Objects.equals(statue2, "下架") && Objects.equals(statue, "上架")) {//只有从下架变成上架的情况，商品上架的时间才会改变
                if (goodsNum == 0){
                    //如果库存为0，不让你上架,把上架改为下架
                    return 2;
                }
                //开始写入数据库
                goodsMapper.modifyGoodsAndTime(price, goodsMessage, goodsName, goodsType, goodsNum, goodsID, statue);
            }
            else {
                //开始写入数据库
                goodsMapper.modifyGoods(price, goodsMessage, goodsName, goodsType, goodsNum, goodsID, statue);
            }
            if (goodsNum == 0) {
                if (Objects.equals(statue, "上架")) {
                    //上架改为下架
                    goodsMapper.modifyGoods(price, goodsMessage, goodsName, goodsType, goodsNum, goodsID, "下架");
                }

            }
            //把客户购物车里面的商品也修改了
            userMapper userMapper = new userSql();
            userMapper.modifyGouwucarGoods(price,goodsMessage,goodsName,goodsID);

            return 1;
        }
    }
    public int updateGoodsUrl(int goodsID,String url)throws Exception{//修改商品图片

        goodsMapper goodsMapper = new goodsSql();
        goodsMapper.modifyGoodsUrl(url, goodsID);
        //修改购物车里面的图片


        return 1;

    }
    public int addGoods(goods goods,users users)throws Exception{
        String goodsName = goods.getGoodsName();
        String goodsMessage = goods.getGoodsMessage();
        int goodsNum = goods.getGoodsNum();
        float price = goods.getPrice();

        int goodsNameLenth = goodsName.length();//初始字符串长度
        int goodsMessageLenth = goodsMessage.length();//初始字符串长度

        goodsMessage = goodsMessage.replaceAll("\\s+", "");//去除所有的空格
        goodsName = goodsName.replaceAll("\\s+", "");//去除所有的空格

        int goodsNameLenth2 = goodsName.length();//后来的字符串长度
        int goodsMessageLenth2 = goodsMessage.length();//后来的字符串长度

        if ((goodsNameLenth != goodsNameLenth2) || (goodsMessageLenth != goodsMessageLenth2) || (goodsNum < 0) || (price == 0) || (goodsName.isEmpty())|| (goodsMessage.isEmpty())){
            //价格为空，库存为空，库存为负数，商品信息含有空格，商品名称含有空格，商品信息商品名称为空,返回0
            return 0;
        } else {
            //开始写入数据库
            goodsMapper goodsMapper = new goodsSql();
            goodsMapper.addGoods(goods.getPrice(), goods.getGoodsMessage(), goods.getGoodsName(), goods.getGoodsType(), goods.getGoodsNum(), users.getUserID(), users.getShopName());
            return 1;
        }
    }
    public int deleteGoods(int[] ids) throws Exception {//批量删除商品
        goodsMapper goodsMapper = new goodsSql();
        //把客户在购物车的商品也删除了
        userMapper userMapper = new userSql();
        for (int i = 0; i < ids.length; i++) {
            userMapper.deleteGouwucarGoodsByGoodsID(ids[i]);
        }
        goodsMapper.deleteGoods(ids);
        return 1;
    }
    public int deleteGoods2(int ids) throws Exception {//单个删除商品
        goodsMapper goodsMapper = new goodsSql();
        //把客户在购物车的商品也删除了
        userMapper userMapper = new userSql();
        userMapper.deleteGouwucarGoodsByGoodsID(ids);

        goodsMapper.deleteGoods2(ids);
        return 1;
    }
    public PageBean<goods> selectByPage(int currentPage,int pageSize) throws Exception {
        goodsMapper goodsMapper = new goodsSql();
        //把未支付的订单的库存还回来
        userMapper userMapper = new userSql();
        ResultSet rs = userMapper.selectAllOrderForm();
        while (rs.next()){
            if(((rs.getInt("statue") == 0) || (rs.getInt("statue") == 2)) && (rs.getInt("goods_handle") == 0)){
                //没有支付成功的,还没有被处理的,已经取消了的订单
                if((rs.getInt("statue") == 0)){
                    Timestamp time = rs.getTimestamp("time");
                    // 获取当前时间的Date
                    Date currentDate = new Date();
                    // 比较时间
                    if (time.before(currentDate)) {
                        //时间过了
                        int goodsID = rs.getInt("goods_id");
                        int goodsNum = rs.getInt("goods_num");
                        ResultSet rs2 = goodsMapper.selectByID(goodsID);
                        int goodsNum2 = 0;
                        if (rs2.next()) {
                            goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                        }
                        goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                        userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                    }
                }
                else if ((rs.getInt("statue") == 2)) {
                    int goodsID = rs.getInt("goods_id");
                    int goodsNum = rs.getInt("goods_num");
                    ResultSet rs2 = goodsMapper.selectByID(goodsID);
                    int goodsNum2 = 0;
                    if (rs2.next()) {
                        goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                    }
                    goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                    userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                }

            }
        }


        //计算开始索引
        int begin = (currentPage-1) * pageSize;
        int size = pageSize;
        List<goods> rows = goodsMapper.selectByPage(begin, size);
        //查询总记录数
        int totalCount = goodsMapper.selectTotalCounts();

        //封装对象
        PageBean<goods> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);


        return pageBean;
    }
    public PageBean<goods> onSubmit(int currentPage,int pageSize,goods goods) throws Exception {
        goodsMapper goodsMapper = new goodsSql();
        //把未支付的订单的库存还回来
        userMapper userMapper = new userSql();
        ResultSet rs = userMapper.selectAllOrderForm();
        while (rs.next()){
            if(((rs.getInt("statue") == 0) || (rs.getInt("statue") == 2)) && (rs.getInt("goods_handle") == 0)){
                //没有支付成功的,还没有被处理的,已经取消了的订单
                if((rs.getInt("statue") == 0)){
                    Timestamp time = rs.getTimestamp("time");
                    // 获取当前时间的Date
                    Date currentDate = new Date();
                    // 比较时间
                    if (time.before(currentDate)) {
                        //时间过了
                        int goodsID = rs.getInt("goods_id");
                        int goodsNum = rs.getInt("goods_num");
                        ResultSet rs2 = goodsMapper.selectByID(goodsID);
                        int goodsNum2 = 0;
                        if (rs2.next()) {
                            goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                        }
                        goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                        userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                    }
                }
                else if ((rs.getInt("statue") == 2)) {
                    int goodsID = rs.getInt("goods_id");
                    int goodsNum = rs.getInt("goods_num");
                    ResultSet rs2 = goodsMapper.selectByID(goodsID);
                    int goodsNum2 = 0;
                    if (rs2.next()) {
                        goodsNum2 = rs2.getInt("goods_num");//获取原来的库存
                    }
                    goodsMapper.modifyGoodsNum((goodsNum + goodsNum2),goodsID);
                    userMapper.updateOrderFormHandleStatue(rs.getInt("order_id"));//把处理过的订单设置为1
                }

            }
        }
        //计算开始索引
        int begin = (currentPage-1) * pageSize;
        int size = pageSize;

        List<goods> rows = goodsMapper.onSubmit(begin, size, goods);
        //查询总记录数
        int totalCount = goodsMapper.selectTotalCountsSubmit(goods);

        //封装对象
        PageBean<goods> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);


        return pageBean;
    }
    public int uploadComment(String goodsComment,int greatNum,int userID,int goodsID)throws Exception{//上传评论
        goodsMapper goodsMapper = new goodsSql();
        //先把评论里面的空格去掉，看看是不是空字符串，是就不写进去

        goodsComment = goodsComment.replaceAll("\\s+", "");//去除所有的空格
        int goodsCommentLenth2 = goodsComment.length();//后来的字符串长度

        if(goodsCommentLenth2 == 0){
            //全是空格，设置为:客户暂未发表评论
            goodsComment = "该客户暂未发表评论";
        }
        goodsMapper.insertGoodsComment(goodsComment,goodsID,userID);//插入到订单评论中
        if(greatNum == 1){
            //客户给好评
            ResultSet rs = goodsMapper.selectByID(goodsID);//查找一下订单原来的好评数
            int goodsGreat = 0;
            if(rs.next()){
                goodsGreat = rs.getInt("goods_great");
            }
            goodsMapper.modifyGoodsGreat(goodsGreat+1,goodsID);//修改好评数
        }
        return 1;
    }
    public int selectGoodsNum(int goodsID)throws Exception {
        goodsMapper goodsMapper = new goodsSql();
        ResultSet rs = goodsMapper.selectByID(goodsID);
        int num = 0;
        if (rs.next()) {
            num = rs.getInt("goods_num");
        }
        return num;
    }
    public int cancelOrder(orderForm orderForm, users users)throws Exception {//退货订单
        goodsMapper goodsMapper = new goodsSql();
        ResultSet rs = goodsMapper.selectByID(orderForm.getGoodsID());
        int userMaiID = 0;
        if(rs.next()){
            userMaiID = rs.getInt("id");
        }
        goodsMapper.insertCancelOrder(orderForm.getGoodsComment(),orderForm.getGoodsName() ,orderForm.getGoodsID(),users.getUserID(),userMaiID,orderForm.getPrice(),orderForm.getGoodsNum(),users.getUserName(),users.getUserPhone(),users.getUserAddress(),orderForm.getOrderID());//添加到退货订单中
        //把订单的状态修改一下
        userMapper userMapper = new userSql();
        userMapper.updateOrderFormStatue3(orderForm.getOrderID());//把订单状态改为正在退款
        return 1;
    }
    public int agreeCancelOrder(cancelOrder cancelOrder, users users)throws Exception {//同意退款退货
        goodsMapper goodsMapper = new goodsSql();
        //把退货订单状态改为1，把客户订单状态改为4，退钱，销量减num，库存加num
        goodsMapper.modifyCancelOrderStatue(1,cancelOrder.getOrderID());//把状态改为1
        userMapper userMapper = new userSql();
        ResultSet rs = userMapper.selectAllById(cancelOrder.getUserBuyID());
        int sum = 0;
        if(rs.next()){
            sum = rs.getInt("money");//现在的钱
        }
        int totalMoney = sum + cancelOrder.getTotalPrice();//现在该有的钱
        userMapper.updateUserMoney(totalMoney,cancelOrder.getUserBuyID());//更新钱

        users.setMoney(totalMoney);
        //把订单的状态修改一下
        userMapper.updateOrderFormStatue4(cancelOrder.getOrderFormID());//把订单状态改为成功退款
        ResultSet rs2 = goodsMapper.selectByID(cancelOrder.getGoodsID());
        int num = 0;//原来的销量
        int kuCun = 0;//原来的库存
        if(rs2.next()){
            num = rs2.getInt("goods_xiaoliang");
            kuCun = rs2.getInt("goods_num");
        }
        goodsMapper.modifyGoodsXiaoLiang((num-cancelOrder.getGoodsNum()),cancelOrder.getGoodsID());//更新销量
        goodsMapper.modifyGoodsNum(kuCun+cancelOrder.getGoodsNum(),cancelOrder.getGoodsID());//更新库存
        return 1;
    }
    public int selectGoodsMessage(goods goods)throws Exception{
        goodsMapper goodsMapper = new goodsSql();
        ResultSet rs = goodsMapper.selectByID(goods.getGoodsID());
        int num = 0;
        if(rs.next()){
            num = rs.getInt("look_num");//原来的浏览量
        }
        goodsMapper.modifyGoodsLookNum(num+1,goods.getGoodsID());
        return 1;
    }
    public List<goodsComment> lookComments(goods goods)throws Exception{
        goodsMapper goodsMapper = new goodsSql();
        return goodsMapper.lookGoodsComment(goods.getGoodsID());
    }
    public List<goods_type> showAllGoodsType()throws Exception{
        goodsMapper goodsMapper = new goodsSql();
        return goodsMapper.selectAllGoodsType();
    }
    public int addGoodsType(goods_type goods_type)throws Exception{
        String type = goods_type.getType();
        int goodsID = goods_type.getGoodsID();

        int typeLenth = type.length();//初始字符串长度

        type = type.replaceAll("\\s+", "");//去除所有的空格

        int typeLenth2 = type.length();//后来的字符串长度

        if ((typeLenth != typeLenth2) || typeLenth2 == 0){
            //含有空格或者是空字符串，返回0
            return 0;
        } else {
            //开始写入数据库
            goodsMapper goodsMapper = new goodsSql();
            goodsMapper.addGoodsType(type,goodsID);
            return 1;
        }
    }
}
